// Mechanicoder
// 2025年3月10日

#include "widget_select.h"
#include "ui_widget_select.h"
#include "model_list.h"

#include <AIS_InteractiveContext.hxx>
#include <TopoDS_Shape.hxx>

#include <QPushButton>

struct WidgetSelect::Data
{
    Ui::WidgetSelect* ui;
    QString groupName;
    Handle(AIS_InteractiveContext) context;

    std::vector<TopoDS_Shape> selectedShapes;
};

WidgetSelect::WidgetSelect(QWidget* parent)
    : _d(std::make_shared<Data>()), QWidget(parent)
{
    _d->ui = new Ui::WidgetSelect;
    _d->ui->setupUi(this);

    connect(_d->ui->pushButtonSelect, &QPushButton::clicked, this, &WidgetSelect::OnSelect);
    connect(_d->ui->pushButtonClear, &QPushButton::clicked, this, &WidgetSelect::OnClearSelect);
    updateGeometry();
}

WidgetSelect::~WidgetSelect()
{
}

void WidgetSelect::Setup(const Handle(AIS_InteractiveContext)& context,
    const QString& group_name, const QString& select_button_name)
{
    _d->groupName = group_name;
    _d->context = context;

    _d->ui->pushButtonSelect->setText(select_button_name);
    _d->ui->groupBox->setTitle(group_name);

    _d->ui->listView->SetupContext(context);
}

const std::vector<TopoDS_Shape>& WidgetSelect::GetShapes() const
{
    return _d->selectedShapes;
}

void WidgetSelect::OnSelect()
{
   _d->context->InitSelected();
    TopoDS_Shape selected_shape = _d->context->SelectedShape();
    if (!selected_shape.IsNull())
    {
        _d->selectedShapes.emplace_back(selected_shape);

        QString name;
        switch (selected_shape.ShapeType())
        {
        case TopAbs_EDGE: name = "Edge"; break;
        case TopAbs_FACE: name = "Face"; break;
        default: name = "null"; break;
        }

        _d->ui->listView->RecordModel(
            selected_shape, QString("%1 %2").arg(name).arg(_d->ui->listView->count()));
    }

    _d->ui->groupBox->setTitle(QString("%1 [%2]").arg(_d->groupName).arg(_d->selectedShapes.size()));
}

void WidgetSelect::OnClearSelect()
{
    _d->selectedShapes.clear();
    _d->ui->listView->Clear();

    _d->ui->groupBox->setTitle(QString("%1 [0]").arg(_d->groupName));
}
